package io.renren.modules.security.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.renren.common.exception.RenException;
import io.renren.common.service.impl.BaseServiceImpl;
import io.renren.modules.security.dao.KeywordDao;
import io.renren.modules.security.dao.KeywordTypeDao;
import io.renren.modules.security.dto.SelectKeywordTypeDto;
import io.renren.modules.security.dto.UpdateKeywordTypeDto;
import io.renren.modules.security.entity.Keyword;
import io.renren.modules.security.entity.KeywordType;
import io.renren.modules.security.service.KeywordTypeService;
import jakarta.annotation.Resource;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

@Service
public class KeywordTypeServiceImpl extends BaseServiceImpl<KeywordTypeDao, KeywordType> implements KeywordTypeService {

    @Lazy
    @Resource
    private KeywordDao keywordDao;

    public Page<KeywordType> getPageList(SelectKeywordTypeDto param){
        LambdaQueryWrapper<KeywordType> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StrUtil.isNotBlank(param.getKeywordType()), KeywordType::getKeywordType, param.getKeywordType());
        queryWrapper.orderByDesc(KeywordType::getCreateTime);
        return this.baseDao.selectPage(new Page<>(param.getCurrentPage(), param.getPageSize()), queryWrapper);
    }

    public boolean add(UpdateKeywordTypeDto dto){
        verify(dto);
        KeywordType keywordType = new KeywordType();
        keywordType.setKeywordType(dto.getKeywordType());
        return this.baseDao.insert(keywordType) > 0;
    }

    public boolean update(UpdateKeywordTypeDto dto){
        verify(dto);
        KeywordType keywordType = this.baseDao.selectById(dto.getId());
        if (keywordType == null) {
            throw new RenException("该关键词类型已不存在");
        }
        keywordType.setKeywordType(dto.getKeywordType());
        return this.baseDao.updateById(keywordType) > 0;
    }

    public boolean delete(Long id){
        KeywordType keywordType = this.baseDao.selectById(id);
        if (keywordType == null) {
            throw new RenException("该关键词类型已不存在");
        }
        this.baseDao.deleteById(keywordType);
        LambdaQueryWrapper<Keyword> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Keyword::getKeywordTypeId, keywordType.getId());
        keywordDao.delete(wrapper);
        return true;
    }

    private void verify(UpdateKeywordTypeDto dto){
        LambdaQueryWrapper<KeywordType> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(KeywordType::getKeywordType, dto.getKeywordType());
        queryWrapper.ne(KeywordType::getId, dto.getId());
        if (this.baseDao.selectCount(queryWrapper) > 0) {
            throw new RenException("当前关键词类型已存在！");
        }
    }
}
